package smetana.modules.ui.form.doc;

import com.google.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.pivot.collections.List;
import org.apache.pivot.collections.Sequence;
import org.apache.pivot.wtk.*;
import org.apache.pivot.wtk.Mouse.Button;
import org.apache.pivot.wtkx.WTKX;
import smetana.domain.join.DocReport;
import smetana.domain.raw.Doc;
import smetana.modules.business.BusinessDoc;
import smetana.modules.business.BusinessPivot;
import smetana.modules.ui.actions.DeleteDocumentAction;
import smetana.modules.ui.actions.EditDocumentAction;
import smetana.modules.ui.actions.ExportDocumentAction;
import smetana.modules.ui.actions.PrintDocumentAction;
import smetana.modules.ui.form.AbstractPanel;
import smetana.modules.ui.model.*;
import smetana.modules.ui.model.Cursor;

/**
 * @author dmitry.mamonov
 */
public class DocListPanel extends AbstractPanel {
    final Logger log = Logger.getLogger(getClass());

    @Inject
    EditDocumentAction actionEdit;

    @Inject
    DeleteDocumentAction actionDelete;

    @Inject
    ExportDocumentAction actionExport;

    @Inject
    PrintDocumentAction actionPrint;

    @Inject
    BusinessPivot businessPivot;

    @Inject
    BusinessDoc businessDoc;

    @WTKX
    TableView tableView;

    @Inject
    UIModel uiModel;

    @Inject
    CursorDoc cursorDoc;

    public DocListPanel() {
        super();
    }

    @Override
    public void init() {
        tableView.getTableViewSelectionListeners().add(new TableViewSelectionListener.Adapter() {
            @Override
            public void selectedRangesChanged(TableView tableView, Sequence<Span> previousSelectedRanges) {
                updateActionsStatus();
            }
        });
        tableView.getComponentMouseButtonListeners().add(new ComponentMouseButtonListener.Adapter() {
            @Override
            public boolean mouseClick(Component component, Button button, int x, int y, int count) {
                DocReport docReport = getSelectedDocumentReport();
                cursorDoc.set(docReport);
                if (docReport != null && count == 2) {
                    actionEdit.perform();
                    return true;
                }
                return false;
            }

        });
        tableView.getTableViewSelectionListeners().add(new TableViewSelectionListener.Adapter(){
            @Override
            public void selectedRangesChanged(TableView tableView, Sequence<Span> previousSelectedRanges) {
                cursorDoc.set((Doc) tableView.getSelectedRow());
            }
        });

        cursorDoc.getProducers().add(new smetana.modules.ui.model.Cursor.Producer<Doc>() {
            @Override
            public void onCurrentUpdated(Cursor<Doc> docCursor, Doc updatedValue) {
                refresh();
            }

            @Override
            public void onCurrentDeleted(Cursor<Doc> docCursor) {
                refresh();
                if (tableView.getTableData().getLength()>0){
                    tableView.setSelectedIndex(0);
                }
            }

            @Override
            public void onRefreshFor(Cursor<Doc> docCursor, Doc targetValue) {
                refresh();
                //TODO why I can't select element by value?
                int index = ((List<Object>)tableView.getTableData()).indexOf(targetValue);
                log.info("Seelected index: "+index);
                tableView.setSelectedIndex(index);
            }
        });
        refresh();
    }

    @SuppressWarnings("unchecked")
    public DocReport getSelectedDocumentReport() {
        DocReport docReport = (DocReport) tableView.getSelectedRow();
        return docReport;
    }

    @SuppressWarnings("unchecked")
    public void selectDocumentReport(Doc doc) {
        DocReport docReport = businessDoc.findDocReportById(doc.getId());
        List<DocReport> tableViewList = ((List<DocReport>) tableView.getTableData());
        int index = tableViewList.indexOf(docReport);
        tableView.setSelectedIndex(index);
    }

    private void updateActionsStatus() {
        setActionsEnabled(tableView.getSelectedIndex() >= 0);
    }

    //TODO статус некоторых action-ов может быть составной, это нужно учитывать при реализации action.

    private void setActionsEnabled(boolean enabled) {
        actionEdit.setEnabled(enabled);
        actionDelete.setEnabled(enabled);
        actionExport.setEnabled(enabled);
        actionPrint.setEnabled(enabled);
    }

    public void refresh() {
        tableView.setTableData(businessPivot.pivotListOfDocReports());
        updateActionsStatus();
    }
}
